package com.carl.dao;

import java.util.List;

import org.bson.types.ObjectId;

import com.carl.bean.UserInfo;
import com.carl.dao.UserInfoDao;
import com.google.code.morphia.Datastore;
import com.google.code.morphia.Key;
import com.google.code.morphia.mapping.Mapper;
import com.google.code.morphia.query.Query;
import com.google.code.morphia.query.UpdateOperations;
import com.google.code.morphia.query.UpdateResults;
import com.mongodb.WriteResult;

public class UserInfoDao extends BasicDao<UserInfo> {

	
	protected UserInfoDao(Datastore ds) {
		super(ds);
	}
	
	/**
	 * 保存用户
	 * @param userInfo
	 * @return
	 */
	public Key<UserInfo> saveUser(UserInfo userInfo){
		Key<UserInfo> keyInfo = ds.save(userInfo);
		return keyInfo;
		
	};
	
	/**
	 * 删除用户信息
	 * @param userInfo
	 * @return
	 */
	public String deleteUser(UserInfo userInfo){
		Query<UserInfo> query = ds.createQuery(UserInfo.class);
		WriteResult result = null;
		
		ObjectId id = userInfo.getId();
		if(id != null){
			query.field(Mapper.ID_KEY).equal(ObjectId.massageToObjectId(id));
			result = ds.delete(query);
		}else{
			result = this.delete(userInfo);
		}
		return (String) result.getField("err");
	}
	
	/**
	 * 更新用户信息，返回的是被更新了的用户信息列表
	 * @param userInfo
	 * @return
	 */
	public UpdateResults<UserInfo> updateUserInfo(UserInfo userInfo){
		
		UpdateOperations<UserInfo> ops = getUpdateOperOfEntity(userInfo);
		Query<UserInfo> query = getEntityQuery(userInfo);
		
		UpdateResults<UserInfo> upList = ds.update(query, ops);
		
		return upList;
	}
	
	
	/**
	 * 根据userInfo中的属性值来做查询
	 * @param userInfo
	 * @return
	 */
	public List<UserInfo> findUser(UserInfo userInfo, Integer offset, Integer limit){
		Query<UserInfo> userQuery = getEntityQuery(userInfo);
		if(offset != null && limit != null){
			userQuery.offset(offset).limit(limit);
		}
		
		List<UserInfo> result = userQuery.asList();
		return result;
	}
	
	/**
	 * 只返回一条记录
	 * @param userInfo
	 * @return
	 */
	public UserInfo findUserOne(UserInfo userInfo){
		
		Query<UserInfo> userQuery = getEntityQuery(userInfo);
		
		UserInfo user = this.findOne(userQuery);
		
		return user;
	}
	
}
